<template>
  <el-row>
    <el-row v-if="admin">
      <div class="default-text">
        {{ $t('common.auditOperaWords.tip') }}
      </div>
    </el-row>
    <el-row v-else>
      <el-card v-loading="stateLoading">
        <el-row>
          <el-col :span="8" style="font-size: 30px;text-align: left;line-height: 40px">
            {{ $t('common.auditOperaWords.auditTitle') }}
          </el-col>
          <el-col :span="16" style="text-align: right">
            <el-button v-if="attendanceBtn" @click="goAttendance">
              {{ $t('common.auditOperaWords.attendance') }}
            </el-button>
            <el-button v-if="(isSignIn === 0 || isSignIn === 2 || isSignIn === 3) && singInBtn" :disabled="isAllocate === 2" :loading="inLoading" type="primary" @click="goSignIn">
              {{ $t('common.auditOperaWords.signIn') }}
            </el-button>
            <el-button v-if="(isSignIn === 1) && singInBtn" :loading="outLoading" type="primary" @click="goSignOut">
              {{ $t('common.auditOperaWords.signOut') }}
            </el-button>
          </el-col>
        </el-row>
        <el-divider />
        <el-row v-if="isSignIn === 0 || isSignIn === 2 || isSignIn === 3" style="text-align: center">
          <el-row style="margin-bottom: 20px">
            {{ signInData['riskAuditDateStr'] }} {{ $t('common.auditOperaWords.auditAllocatTime') }} :
          </el-row>
          <el-row>
            {{ dateStr(signInData['amAllocateBeginTime']) }} - {{ dateStr(signInData['amAllocateEndTime']) }}
          </el-row>
          <el-row style="margin-bottom: 20px">
            {{ dateStr(signInData['pmAllocateBeginTime']) }} - {{ dateStr(signInData['pmAllocateEndTime']) }}
          </el-row>
          <el-row v-if="isSignIn === 0 && signInData['residueBeginAllocateDate']">
            {{ $t('common.auditOperaWords.remain') }}
            <span>{{ signInData["residueBeginAllocateDate"] }}</span>
            {{ $t('common.auditOperaWords.startAllocate') }},
            <span>{{ $t('common.auditOperaWords.signInTime') }}</span> !
          </el-row>
          <el-row v-if="isSignIn === 0 && !signInData['residueBeginAllocateDate']">
            {{ $t('common.auditOperaWords.signInWorking') }}
          </el-row>
          <el-row v-if="isSignIn === 3">
            {{ $t('common.auditOperaWords.siginoutSystem') }}
          </el-row>
        </el-row>
        <el-row v-if="isSignIn === 1 && isAllocate === 0" style="text-align: center">
          <el-row style="margin-bottom: 20px">
            {{ signInData['riskAuditDateStr'] }} {{ $t('common.auditOperaWords.auditAllocatTime') }} :
          </el-row>
          <el-row>
            {{ dateStr(signInData['amAllocateBeginTime']) }} - {{ dateStr(signInData['amAllocateEndTime']) }}
          </el-row>
          <el-row style="margin-bottom: 20px">
            {{ dateStr(signInData['pmAllocateBeginTime']) }} - {{ dateStr(signInData['pmAllocateEndTime']) }}
          </el-row>
          <el-row>
            {{ $t('common.auditOperaWords.remain') }}
            <span>{{ signInData["residueBeginAllocateDate"] }}</span>
            {{ $t('common.auditOperaWords.startAllocate') }},
            <span>{{ $t('common.auditOperaWords.signInTime') }}</span> !
          </el-row>
        </el-row>
        <el-row v-if="isSignIn === 1 && (isAllocate === 1 || isAllocate === 2)">
          <el-button-group>
            <el-button
              v-for="item in $t('common.auditOperaCommon')"
              :key="item['value']"
              :type="item['value'] === searchForm.status ? 'primary' : ''"
              @click="changeStatus(item['value'])"
            >
              {{ item['name'] }}
            </el-button>
          </el-button-group>
          <el-divider />
          <el-row>
            <el-form ref="searchForm" :inline="true" :model="searchForm">
              <el-form-item :label="$t('financeModule.list.table.askTime')">
                <el-date-picker
                  v-model="time"
                  type="daterange"
                  range-separator="~"
                  :start-placeholder="$t('common.startDate')"
                  :end-placeholder="$t('common.endDate')"
                />
              </el-form-item>
              <el-form-item :label="$t('reviewRiskList.searchModule.effectTime')">
                <el-date-picker
                  v-model="approveTime"
                  type="daterange"
                  range-separator="~"
                  :start-placeholder="$t('common.startDate')"
                  :end-placeholder="$t('common.endDate')"
                />
              </el-form-item>
              <el-form-item :label="$t('financeModule.list.table.creditOrderNo')">
                <el-input v-model="searchForm.creditOrderNo" clearable :placeholder="$t('financeModule.list.prompt.letterReview')" :maxlength="50" />
              </el-form-item>
              <el-form-item :label="$t('financeModule.list.table.mobile')">
                <el-input v-model="searchForm.userPhone" clearable :placeholder="$t('financeModule.list.prompt.mobile')" :maxlength="50" />
              </el-form-item>

              <el-form-item :label="$t('usrModule.list.table.channelSource')">
                <el-select v-model="searchForm.channel" clearable :placeholder="$t('usrModule.list.prompt.channelSource')" @change="setSource">
                  <el-option
                    v-for="item in $t('usrModule.list.source')"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('usrModule.list.table.promotionMethod')">
                <el-select v-model="searchForm.promotionTypeStr" clearable multiple collapse-tags :placeholder="$t('usrModule.list.prompt.promotionMethod')">
                  <el-option
                    v-for="item in promotionData"
                    :key="item.value"
                    :label="item.desc"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('usrModule.list.table.referrer')">
                <el-input v-model="searchForm.referrerName" clearable :placeholder="$t('usrModule.list.prompt.referrer')" :maxlength="50" />
              </el-form-item>
              <el-row>
                <el-button type="primary" @click="search">
                  {{ $t('common.search') }}
                </el-button>
                <el-button @click="reset">
                  {{ $t('common.reset') }}
                </el-button>
              </el-row>
            </el-form>
          </el-row>
        </el-row>
      </el-card>
      <el-card v-if="isSignIn === 1 && (isAllocate === 1 || isAllocate === 2)">
        <el-table
          v-loading="loading"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          :data="tableData"
          border
          :stripe="true"
          style="width: 100%"
          @sort-change="changeSort"
        >
          <el-table-column
            fixed="left"
            prop="creditOrderNo"
            :label="tableText['reviewOrderNo']"
            min-width="170"
          >
            <template slot-scope="scope">
              <el-button type="text" :style="{'color' : scope.row['creditOrderLockStatus'] === true ? '#de0606' : ''}" @click="auth(scope.row)">
                {{ scope.row.creditOrderNo }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            :label="tableText['createTime']"
            sortable
            min-width="180"
          />
          <el-table-column
            prop="userPhone"
            :label="tableText['userPhone']"
            min-width="150"
          />
          <el-table-column
            prop="userGrade"
            :label="tableText['userLevel']"
            min-width="150"
          />
          <el-table-column
            prop="channelStr"
            :label="tableText['channelSource']"
            min-width="150"
          />
          <el-table-column
            prop="promotionTypeStr"
            :label="tableText['promotionMethod']"
            min-width="150"
          />
          <el-table-column
            prop="referrerName"
            :label="tableText['referrer']"
            min-width="150"
          />
          <el-table-column
            prop="loanProductType"
            :label="tableText['productType']"
            min-width="200"
          >
            <template slot-scope="scope">
              {{ setValue(scope.row['loanProductType'], 'productTypes') }}
            </template>
          </el-table-column>
          <el-table-column
            prop="applyMonth"
            :label="tableText['periodsNumber']"
            min-width="150"
          />
          <el-table-column
            prop="applyMoney"
            :label="tableText['loanAmount']"
            min-width="150"
          />
          <el-table-column
            prop="loanDays"
            :label="tableText['loanPeriod']"
            min-width="150"
          >
            <template slot-scope="scope">
              {{ (scope.row['loanDays'] && scope.row['applyMonth']) ? (scope.row['loanDays'] * scope.row['applyMonth']) : '' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="stageName"
            :label="tableText['stage']"
            min-width="150"
          />
          <el-table-column
            prop="currentAuditStaffName"
            :label="tableText['stageLetterReviewer']"
            min-width="150"
          />
          <el-table-column
            prop="operationResult"
            :label="tableText['stageAuditResults']"
            min-width="150"
          >
            <template slot-scope="scope">
              {{ setValue(scope.row['operationResult'], 'currentStageRes') }}
            </template>
          </el-table-column>
          <el-table-column
            prop="operationRemark"
            :label="tableText['opinion']"
            min-width="150"
          />
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="searchForm.currentPage"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="searchForm.pageSize"
            :total="totalNumber"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </el-row>
  </el-row>
</template>

<script>
import { querySiginStatus, goSignIn, goSignOut, getAuditList, getCurrentCreditAuditStaff, lockUnauditCreditOrder } from '@/api/risk'
import { allPackage } from '@/api/user'
import { formatDate, ObjToQueryString } from '@/utils/method'
export default {
  name: 'OperPlatCommon',
  data() {
    return {
      loading: false,
      admin: false,
      outLoading: false,
      inLoading: false,
      isAllocate: false,
      stateLoading: false,
      singInBtn: true,
      attendanceBtn: true,
      isSignIn: 2,
      signInData: {},
      tableText: {},
      totalNumber: 0,
      time: null,
      approveTime: null,
      tableData: [],
      allPackageData: [],
      promotionData: [],
      searchForm: this.params()
    }
  },
  mounted() {
    this.tableText = this.$t('reviewRiskList.tableModule')
    this.getLoginInfo()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        status: 1,
        applyDateBegin: null,
        applyDateEnd: null,
        approveEffectDayBegin: null,
        approveEffectDayEnd: null,
        userPhone: null,
        creditOrderNo: null,
        channel: null,
        promotionTypeStr: null,
        referrerName: null,
        isAscend: null
      }
    },
    getLoginInfo() {
      const roleOutputBOS = JSON.parse(sessionStorage.getItem('loginInfo'))['roleOutputBOS']
      const state = roleOutputBOS.filter(v => {
        return v.id === 1
      })
      if (state && state.length > 0) {
        this.admin = true
      } else {
        this.admin = false
        this.querySignStatus()
        this.setBtn()
        this.getAllPackage()
      }
    },
    querySignStatus() {
      this.stateLoading = true
      querySiginStatus()
        .then(res => {
          this.stateLoading = false
          if (res.success) {
            this.signInData = res.data
            this.signInData['riskAuditDateStr'] = this.signInData['riskAuditDate'] ? formatDate(new Date(this.signInData['riskAuditDate']), 'yyyy-MM-dd') : ''
            this.isSignIn = res.data['signInState']
            this.isAllocate = res.data['allocateState']
            if (this.isSignIn === 1 && (this.isAllocate === 1 || this.isAllocate === 2)) {
              this.getData()
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    setBtn() {
      const roleOutputBOS = JSON.parse(sessionStorage.getItem('loginInfo'))['roleOutputBOS']
      const singIn = roleOutputBOS.filter(v => {
        return v.id === 14
      })
      this.singInBtn = singIn && singIn.length > 0
      const attendance = roleOutputBOS.filter(v => {
        return v.id === 15
      })
      this.attendanceBtn = attendance && attendance.length > 0
    },
    dateStr(data) {
      if (data && data.length === 19) {
        return formatDate(new Date(data), 'hh:mm:ss')
      } else {
        return data
      }
    },
    changeStatus(data) {
      this.searchForm.status = data
      this.searchForm.currentPage = 1
      this.getData()
    },
    changeSort(val) {
      this.searchForm.isAscend = val.order === 'ascending'
      this.search()
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.time = null
      this.getData()
    },
    goAttendance() {
      this.$router.push({
        name: 'riskAttendance'
      })
    },
    goSignIn() {
      this.inLoading = true
      goSignIn()
        .then(res => {
          this.inLoading = false
          if (res.success) {
            this.querySignStatus()
            this.getData()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.inLoading = false
          this.$message.error(err.message)
        })
    },
    goSignOut() {
      this.outLoading = true
      goSignOut()
        .then(res => {
          this.outLoading = false
          if (res.success) {
            this.querySignStatus()
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.outLoading = false
          this.$message.error(err.message)
        })
    },
    searchData() {
      const data = {
        status: this.searchForm.status,
        userPhone: this.searchForm.userPhone,
        creditOrderNo: this.searchForm.creditOrderNo,
        channel: this.searchForm.channel,
        referrerName: this.searchForm.referrerName,
        isAscend: this.searchForm.isAscend,
        pageSize: this.searchForm.pageSize,
        currentPage: this.searchForm.currentPage
      }
      if (this.time && this.time.length > 1) {
        data['applyDateBegin'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['applyDateEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['applyDateBegin'] = null
        data['applyDateEnd'] = null
      }
      if (this.approveTime && this.approveTime.length > 1) {
        data['approveEffectDayBegin'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['approveEffectDayEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['approveEffectDayBegin'] = null
        data['approveEffectDayEnd'] = null
      }
      return data
    },
    getData() {
      this.loading = true
      getAuditList(this.searchData())
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    getAllPackage() {
      allPackage()
        .then(res => {
          if (res.success) {
            this.allPackageData = res.data
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    setSource() {
      const channel = this.searchForm.channel
      if (channel === 1) {
        this.promotionData = this.$t('usrModule.list.method')
      } else if (channel === 2) {
        this.promotionData = this.$t('usrModule.list.method1')
      } else if (channel === 3) {
        this.promotionData = []
        const arr = this.allPackageData.filter(v => {
          return v['mediaSource'] !== null
        })
        const node = []
        arr.forEach(v => {
          node.push({
            desc: v['mediaSource'],
            value: v['mediaSource']
          })
        })
        this.promotionData = node
      } else {
        this.promotionData = []
      }
      this.searchForm.promotionTypeStr = null
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    setValue(val, data) {
      const name = this.$t(`reviewRiskList.tableModule.${data}`).filter(item => {
        return item.value === val
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    auth(item) {
      if (item.status === 9) {
        const loginInfoId = JSON.parse(sessionStorage.getItem('loginInfo'))['id']
        this.loading = true
        if (loginInfoId === 1) {
          this.lockOrder(item)
        } else {
          getCurrentCreditAuditStaff()
            .then(res => {
              if (res.success) {
                if (res.data['stageId'] === item['stageId'] && res.data['productTypeList'].indexOf(item['loanProductType'] - 0) > -1) {
                  this.lockOrder(item)
                } else {
                  const data = {
                    from: 'riskListView',
                    status: item['status'],
                    userId: item['userId'],
                    orderId: item['id'],
                    orderNo: item['creditOrderNo']
                  }
                  const para = ObjToQueryString(data)
                  window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
                }
              } else {
                this.loading = false
                this.$message.error(res.message)
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error(err.message)
            })
        }
      } else {
        const paramData = {
          from: 'riskListView',
          status: item['status'],
          userId: item['userId'],
          orderId: item['id'],
          orderNo: item['creditOrderNo']
        }
        const para = ObjToQueryString(paramData)
        window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
      }
    },
    lockOrder(item) {
      lockUnauditCreditOrder(item.id)
        .then(res => {
          if (res.success) {
            this.loading = false
            if (res.data['showAuditButton']) {
              const paramData = {
                from: 'riskList',
                status: item['status'],
                userId: item['userId'],
                orderId: item['id'],
                orderNo: item['creditOrderNo']
              }
              const para = ObjToQueryString(paramData)
              window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
            } else {
              const paramData = {
                from: 'riskListView',
                status: item['status'],
                userId: item['userId'],
                orderId: item['id'],
                orderNo: item['creditOrderNo']
              }
              const para = ObjToQueryString(paramData)
              window.open(`${window.location.origin + window.location.pathname}#/usr/auth?${para}`, '_blank')
            }
          } else {
            this.loading = false
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
.default-text{
  width: 100%;
  font-size: 30px;
  text-align: center;
  padding-top: 100px;
}
</style>
